package secondBrush.array;

import java.util.Arrays;

public class E03Leetcode977 {
    public int[] sortedSquares(int[] nums) {
        for (int i = 0; i < nums.length; i++) {
            nums[i] = nums[i] * nums[i];
        }
        Arrays.sort(nums);
        return nums;

    }

    public int[] sortedSquares1(int[] a) {
        for (int i = 0; i < a.length; i++) {
            if (a[i] < 0) {
                a[i] = a[i] * -1;
            }

        }
        for (int low = 1; low < a.length; low++) {
            int t = a[low];
            int i = low - 1;
            //找出待插入位置，空出来
            while (i >= 0 && t < a[i]) {
                a[i + 1] = a[i];
                i--;
            }
            //找到了
            if (i != low - 1) {
                a[i + 1] = t;
            }
        }
        for (int i = 0; i < a.length; i++) {
            a[i] = a[i] * a[i];
        }


        return a;

    }

    public static int[] sortedSquares2(int[] nums) {
        int length = nums.length;
        int i = 0, j = length - 1, k = length - 1;
        int[] result = new int[length];

        while (i < j) {
            if (nums[i] * nums[i] < nums[j] * nums[j]) {
                result[k--] = nums[j] * nums[j];
                --j;
            } else if (nums[i] * nums[i] > nums[j] * nums[j]) {
                result[k--] = nums[i] * nums[i];
                ++i;
            }
        }

        return result;


    }

    public static void main(String[] args) {
        int[] nums = {-4, -1, 0, 3, 10};
        System.out.println(Arrays.toString(sortedSquares2(nums)));

    }

}
